import 字段包.UserBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//修改跳转程序
@WebServlet("/edit")
public class EditServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        UserBean user = new UserBean();
        String birthday= request.getParameter("birthday");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date =null;
        try {
            date =sdf.parse(birthday);
        } catch (ParseException e) {
            throw  new RuntimeException(e);
        }
        user .setId(Integer.parseInt(request.getParameter("id")));
        user.setUserCode(request.getParameter("userCode"));
        user.setUserName(request.getParameter("userName"));
        user.setuserPassword(request.getParameter("userPassword"));
        user.setGender(Integer.parseInt(request.getParameter("gender")));
        user.setBirthday(date);
        user.setPhone(request.getParameter("phone"));
        user.setAddress(request.getParameter("address"));
        user.setUserRole(Integer.parseInt(request.getParameter("userRole")));
        UserDao userDao = new UserDao();
        int result = userDao.updateUser(user);
        if (result > 0 ){
            System.out.println("修改成功");
            response.sendRedirect("main");
        }else{
            System.out.println("修改失败");
            response.sendRedirect("main");
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer  id = Integer.parseInt(request.getParameter("id"));
        UserDao userDao = new UserDao();
        UserBean userBean = userDao.findById(id);
        request.setAttribute("user",userBean);
        request.getRequestDispatcher("/WEB-INF/editUser.jsp").forward(request,response);
    }
}
